package query.io;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import query.io.converters.UserQueryReflexionConverter;
import query.model.UserQuery;

import com.thoughtworks.xstream.XStream;

/**
 * The class used to read the file containing the queries
 */
public class QueriesIO
{
  /** The {@link XStream} instance. */
  private XStream streamInstance;

  /**
   * Instantiates a new queries io.
   */
  public QueriesIO()
  {
    streamInstance = new XStream();
    UserQueryReflexionConverter converter = new UserQueryReflexionConverter(
        streamInstance.getMapper(), streamInstance.getReflectionProvider());
    streamInstance.registerConverter(converter);
    streamInstance.alias("queries", UserQuery.class);
  }

  /**
   * Read queries from file.
   *
   * @param queriesFile the queries file
   * @return the list
   */
  @SuppressWarnings("unchecked")
  public List<UserQuery> readQueriesFromFile(File queriesFile)
  {
    List<UserQuery> fromXML = null;
    try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(queriesFile)))
    {
      fromXML = (List<UserQuery>) streamInstance.fromXML(br);
    }
    catch (IOException e)
    {
      e.getStackTrace();
    }
    return fromXML;
  }
}
